/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.renderer;

import com.jb.web.bean.JBTreeNode;
import com.jb.web.bean.Page;
import com.jb.web.context.WebContext;

import java.util.Iterator;

import com.jb.faces.component.UIComponent;
import com.jb.faces.component.UIComponentBase;


public class TreeNodeRenderer extends DefaultRenderer {
    static final private String treeImageLocation = "resources/images/tree/";
    static final private String line = treeImageLocation + "line.gif";
    static final private String empty = treeImageLocation + "empty.gif";
    static final private String _a = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr>";
    static final private String _b = "<td nowrap valign=\"top\"";
    static final private String _c = "><table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" ><tr><td nowrap >";
    static final private String _d = " style=\"background-image: url('" + line +
        "'); background-repeat:repeat-y;border: 0 ridge #800000\">";
    static final private String _e = " <img src=\"" + empty + "\" border=\"0\" align=\"absbottom\"/></td>";
    static final private String _f = " align=\"absbottom\" name=\"i_img0_6\" />";
   
    public StringBuffer renderBegin(WebContext ctx, UIComponent itemToRender) {
        StringBuffer html = new StringBuffer("<div ");
        JBTreeNode mi = (JBTreeNode) itemToRender;

        html.append(addTagProperty("class", mi.getStyleClass(), null))
            .append(addTagProperty("style", mi.getStyle(ctx), null)).append(" >");

        return html;
    }

    public StringBuffer renderChildren(WebContext ctx, UIComponent itemToRender) {
        JBTreeNode mi = (JBTreeNode) itemToRender;
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(renderNode(ctx, mi));

        if (mi.isOpen()) {
            for (Iterator i = mi.getChildNodes().iterator(); i.hasNext();) {
                stringBuffer.append(((JBTreeNode) i.next()).render(ctx));
            }
        }

        stringBuffer.append("</td></tr></table></div>");

        return stringBuffer;
    }

    public StringBuffer renderEnd(WebContext ctx, UIComponent itemToRender) {
        return new StringBuffer("</div>");
    }

    protected String getLabel(WebContext ctx, JBTreeNode mi) {
        String label =  evaluate(ctx, mi, mi.getValue(ctx));

        if (isEmptyString(label)) {
            label = mi.getId();
        }

        return label;
    }

    private StringBuffer renderNode(WebContext ctx, JBTreeNode node) {
        StringBuffer stringBuffer = new StringBuffer("<div id='"+node.getClientId()+"_c'>"+_a);

        JBTreeNode parentNode =   node.getParentNode();
        JBTreeNode mi =   node;

        if (!mi.isRoot() && !mi.getParentNode().isRoot()) {
            stringBuffer.append(_b);

            if ((parentNode != null) && !parentNode.isLast()) {
                stringBuffer.append(_d);
            } else {
                stringBuffer.append(" >");
            }

            stringBuffer.append(_e);
        }

        stringBuffer.append("<td class=\"jb_tn_dt\" align=\"left\"");
        if(mi.getOnSelect()!=null&&mi.getOnSelect().startsWith("client:"))
            stringBuffer.append(addTagProperty("onSelect", mi.getOnSelect().substring(7), null));


            stringBuffer.append(getEditScript(ctx, mi))
            .append(_c);

        String dest =  evaluate(ctx, mi, mi.getDestination());
        String requestURL = ctx.formURL(dest, mi);

        StringBuffer ajaxCmd = new StringBuffer(" onclick=\"JB.Tree.toggleNode('")
              .append(requestURL).append("','")
              .append(mi.getClientId()).append("','")
              .append(mi.getRootNode().getClientId() +
                "');\"");
        StringBuffer ajaxCmd1 = new StringBuffer(" ondblclick=\"JB.Tree.toggleNode('")
              .append(requestURL).append("','")
              .append(mi.getClientId()).append("','")
              .append(mi.getRootNode().getClientId() +
                "');\"");

        if (!mi.isLeaf()) {
            String defaultMinues = mi.isLast() ? "resources/images/tree/minusbottom.gif" : "resources/images/tree/minus.gif";
            String defaultPlus = mi.isLast() ? "resources/images/tree/plusbottom.gif" : "resources/images/tree/plus.gif";

            String openImg = defaultMinues;
            String collapsedImg = defaultPlus;

            String imageName = mi.isOpen() ? openImg : collapsedImg;

            String imageStr = null;

            if (mi.isOpen()) {
                imageStr = isEmptyString(mi.getOpenIcon()) ? "resources/images/tree/folderopen.gif" : mi.getOpenIcon();
            } else {
                imageStr = isEmptyString(mi.getCloseIcon()) ? "resources/images/tree/folder.gif" : mi.getCloseIcon();
            }

            if (!mi.isRoot()) {
                stringBuffer.append("<SPAN ").append(ajaxCmd).append(" ><img align=\"absbottom\" src=\"")
                            .append(imageName).append("\" /></SPAN>");
            }

            stringBuffer.append("</td><td class=\"jb_tn_dt\"><img ").append(addTagProperty("src", imageStr, null))
                        .append(ajaxCmd1).append(_f);
        } else {
            String imageStr = evaluate(ctx, mi, mi.getIconImage());
            stringBuffer.append("<img");

            if (mi.isLast()) {
                stringBuffer.append(" src=\"resources/images/tree/join.gif\"");
            } else {
                stringBuffer.append(" src=\"resources/images/tree/joinbottom.gif\"");
            }

            stringBuffer.append(" align=\"absbottom\">").append("</td><td class=\"jb_tn_dt\"><img ")
                        .append(addTagProperty("src", imageStr, "resources/images/tree/page.gif"))
                        .append(" align=\"absbottom\" name=\"i_img0_6\" >");
        }

        String label = getLabel(ctx, mi);

        label = "<span " +
            (mi.isSelected() ?   addTagProperty("class", mi.getSelectedStyle(ctx), "jb_tn_txt_selected")
                             :   addTagProperty("class", mi.getStyleClass(), "jb_tn_txt")) + ">" + label + "</span>";

        if (!isEmptyString(dest)) {
            String respId = (String) ctx.getParameter("com.jb.been.tree.render.component");

            if (respId == null) {
                UIComponentBase root = mi.getRootNode();

                while (true) {
                    if ((root == null) || root instanceof Page || (root.getClientId(ctx).indexOf("treeContainer") != -1)) {
                        break;
                    }

                    root = (UIComponentBase) root.getParent();
                }

                if (root != null) {
                    respId = root.getClientId(ctx);
                } else {
                    respId = "";
                }
            }

            ajaxCmd = new StringBuffer(" onclick=\"JB.Tree.selectNode(event,'" + requestURL + "','" + mi.getClientId() +
                    "','" + mi.getRootNode().getClientId() + "');\"");

            label = "&nbsp;<SPAN " + ajaxCmd + " class=\"jb_tn_txt\" >" + label + "</SPAN>";
        } else {
            label = "&nbsp;" + label;
        }

        stringBuffer.append("</td><td class=\"jb_tn_dt\" ").append(addTagProperty("style", mi.getStyle(ctx), null))
                    .append(">").append(label).append("</td><td class=\"jb_tn_dt\">&nbsp;</td></tr></table>");

        return stringBuffer;
    }
}
